<?php

class RoleModel extends Model{
		
	/* 获取所有权限 */
	public function get_role_list(){
		$sql = 'select role_id,role_name,role_desc from role';
		return $this->db->getAll($sql);
	}
	
	/* 获取某一行权限的信息 */
	public function get_role_all($role_id){
		$sql = 'select role_id, role_name, auth_list, role_desc from role where role_id = '. $role_id;
		return $this->db->getRow($sql);
	}
	
	/* 获取所有权限对应的信息 */
	public function get_action_list(){
		$sql = 'select action_id, parent_id, action_code, relevance from admin_action where parent_id = 0';
		$arr = $this->db->getAll($sql);
		
		foreach($arr as $key => $val){
			$priv_arr[$val['action_id']] = $val;
		}
		
		// 按权限组查询子级权限名称
		$list = $this->priv_son($priv_arr);
		for($i=0,$count=count($list); $i<$count; $i++){
			$priv_arr[$list[$i]['parent_id']]['priv'][$list[$i]['action_code']] = $list[$i];
		}
		
		$priv_str = '';
		foreach($priv_arr as $key=>$val){
			$priv_arr[$key]['priv_list'] = join(',', @array_keys($val['priv']));
			foreach($val['priv'] as $k => $v){
				$priv_arr[$key]['priv'][$k]['cando'] = (strpos($priv_str, $val['action_code']) !== false || $priv_str == 'all') ? 1 : 0;
			}
		}
		
		return $priv_arr;
	}
	
	/* 获取某些权限下的所有子权限 */
	public function priv_son($arr){
		$str = '';
		foreach($arr as $key=>$val){
			$str .= $key.',';
		}
		$nums = substr($str, 0, -1);
		
		$sql = 'select action_id, parent_id, action_code, relevance from admin_action where parent_id in (' . $nums . ')';
		return $this->db->getAll($sql);	
	}
	
	/* 增加一行权限管理信息 */
	public function insert($act_list, $username){
		$sql = 'insert into role (role_name, auth_list, role_desc) ' . "values ('".$username."', '$act_list', '".trim($_POST['role_desc'])."')";
		$this->db->query($sql);
		$arr[] = $username;
		$arr[] = $this->db->last_id();
		return $arr;
	}
	
	/* 删除一样权限管理信息 */
	public function delete($id){
		$sql = 'delete from role where role_id = '."'$id'";
		return $this->db->query($sql);
	}
	
	/* 修改一行权限管理信息 */
	public function update($data,$role_id){
		return $this->db->autoExecute($data, 'role', 'update', 'role_id='.$role_id);
	}
	
}


?>